package com.virgo.web.utils;

import jakarta.servlet.http.HttpServletRequest;
import lombok.experimental.UtilityClass;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.io.File;
import java.util.Objects;
import java.util.regex.Pattern;

@UtilityClass
public class IRequestUtils {
	/**
	 * 获取当前http请求对象
	 * @return HttpServletRequest
	 */
	public HttpServletRequest getHttpServletRequest() {
		return ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
	}

	/**
	 * 过滤sql关键词
	 * @param str 原始字符串
	 * @return 过滤后的字符串
	 */
	public String stripSql(String str) {
		if (str != null) {
			//统一转为小写
			String str2 = str.toLowerCase();
			//词语
			String[] SqlStr1 = { "expression", "@import", "select ", "select/*", "update ", "update/*", "delete ",
					"delete/*", "insert ", "insert/*", "updatexml", "concat", "()", "`", "/**/", "union(" };
			for (String s : SqlStr1) {
				if (str2.contains(s)) {
					str = str.replaceAll("(?i)" + s, "");// 正则替换词语
				}
			}
			//StringEscapeUtils.escapeSql 方法新版本废弃维护了
//			str = StringEscapeUtils.escapeSql(str);
		}
		return str;
	}

	/**
	 * 过滤xss脚本
	 * @param value 原始字符串
	 * @return 过滤后的字符串
	 */
	public String stripXSSAndSql(String value) {
		if (value != null) {

			// Avoid anything between script tags
			Pattern scriptPattern = Pattern.compile(
					"<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of
			// e-xpression
			scriptPattern = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
			// Remove any lonesome </script> tag
			scriptPattern = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");
			// Remove any lonesome <script ...> tag
			scriptPattern = Pattern.compile("<[\r\n| | ]*script(.*?)>",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid eval(...) expressions
			scriptPattern = Pattern.compile("eval\\((.*?)\\)",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid e-xpression(...) expressions
			scriptPattern = Pattern.compile("e-xpression\\((.*?)\\)",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid javascript:... expressions
			scriptPattern = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid vbscript:... expressions
			scriptPattern = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
			value = scriptPattern.matcher(value).replaceAll("");
			// Avoid onload= expressions
			scriptPattern = Pattern.compile("onload(.*?)=",
					Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
			value = scriptPattern.matcher(value).replaceAll("");
		}
		return value;
	}

	/**
	 * 获取字符串
	 * @param request 请求对象
	 * @param key 下标
	 * @return 结果
	 */
	public String getString(HttpServletRequest request, String key) {
		String value = request.getParameter(key);
		if (null != value) {
			value = value.trim();
			value = stripSql(value);
			value = stripXSSAndSql(value);
		}
		return value;
	}

	/**
	 * 带默认值的获取字符串
	 * @param request 请求对象
	 * @param key 下标
	 * @param defaultValue 默认值
	 * @return 结果
	 */
	public String getString(HttpServletRequest request, String key,String defaultValue) {
		String value = getString(request, key);
		if(value==null) {
			return defaultValue;
		}
		return value;
	}

	/**
	 * 获取整数
	 * @param request 请求对象
	 * @param key 下标
	 * @return 内容
	 */
	public Integer getInteger(HttpServletRequest request, String key) {
		try {
			String value = getString(request, key);
			if (value != null) {
				return Integer.valueOf(value);
			}
		} catch (Exception ignored) {
		}
		return 0;
	}

	/**
	 * 获取double 值
	 * @param request 请求对象
	 * @param key 下标
	 * @return 内容
	 */
	public Double getDouble(HttpServletRequest request, String key) {
		try {
			String value = getString(request, key);
			if (value != null) {
				return Double.valueOf(value);
			}
		} catch (Exception ignored) {
		}
		return 0D;
	}

	/**
	 * 获取 Float 值
	 * @param request 请求对象
	 * @param key 下标
	 * @return 内容
	 */
	public Float getFloat(HttpServletRequest request, String key) {
		try {
			String value = getString(request, key);
			if (value != null) {
				return Float.valueOf(value);
			}
		} catch (Exception ignored) {
		}
		return 0F;
	}

	/**
	 * 获取 Long 值
	 * @param request 请求对象
	 * @param key 下标
	 * @return 内容
	 */
	public Long getLong(HttpServletRequest request, String key) {
		try {
			String value = getString(request, key);
			if (value != null) {
				return Long.valueOf(value);
			}
		} catch (Exception ignored) {
		}
		return 0L;
	}

	/**
	 * 获取当前请求ip
	 * @return 当前请求ip
	 */
	public String getIpAddr() {
		return getIpAddr(getHttpServletRequest());
	}


	/**
	 * 获取请求的id
	 * @param request 请求对象
	 * @return ip
	 */
	public String getIpAddr(HttpServletRequest request) {

		String ip = request.getHeader("x-forwarded-for");

		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			// 多次反向代理后会有多个ip值，第一个ip才是真实ip
			if (ip.contains(",")) {
				ip = ip.split(",")[0];
			}
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");

		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");

		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");

		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");

		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

	/**
	 * 获取系统资源路径
	 * @return String
	 */
	public String getWebResourcePath() {
		try {
			File path = new File(ResourceUtils.getURL("classpath:").getPath());
			if (!path.exists()) {
				path = new File("");
			}
			return path.getAbsolutePath();

		} catch (Exception ignored) {
		}
		return "";
	}
}
